// 三数之和为 0     [-1,0,1,2,-1,-4]  =>  输出 [[-1,-1,2],[-1,0,1]]

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  let result = []

  nums.sort()

  for (let i = 0; i < nums.length - 2; i++) {
    // 跳过可能重复的值
    if (i > 0 && nums[i] === nums[i - 1]) continue;

    let left = i + 1, right = nums.length - 1
    while (left < right) {
      let sum = nums[i] + nums[left] + nums[right]
      if (sum === 0) {
        result.push([nums[i], nums[left], nums[right]])
        // 跳过可能重复的值
        while (left < right && nums[left] === nums[left + 1]) left++;
        while (left < right && nums[right] === nums[right - 1]) right--;
        left++
        right--
      } else if (sum < 0) {
        left++
      } else {
        right--
      }
    }
  }

  return result
};

console.log(threeSum([0, 0, 0, 0]));
function threeSum(nums) {
  let result = [];
  nums.sort((a, b) => a - b); // 确保数组是按升序排序的

  for (let i = 0; i < nums.length - 2; i++) {
    // 跳过可能重复的值
    if (i > 0 && nums[i] === nums[i - 1]) continue;

    let left = i + 1, right = nums.length - 1;
    while (left < right) {
      let sum = nums[i] + nums[left] + nums[right];
      if (sum === 0) {
        // 当找到一组解时，将其添加到结果中
        result.push([nums[i], nums[left], nums[right]]);

        // 跳过可能重复的值
        while (left < right && nums[left] === nums[left + 1]) left++;
        while (left < right && nums[right] === nums[right - 1]) right--;

        // 移动左右指针，继续寻找下一组解
        left++;
        right--;
      } else if (sum < 0) {
        left++;
      } else {
        right--;
      }
    }
  }

  return result;
}
